package club.janna.hello.sender;

import club.janna.hello.util.DataConvertor;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import org.apache.commons.lang.StringUtils;

/**
 * Created by guopanbo on 18/4/18.
 */
public class DataSender {
    /**
     * 发送数据
     * @param data
     */
    public static boolean sendData(Channel channel, byte[] data, String id) {
        if(data != null && data.length != 0) {
            if (channel != null && channel.isActive()) {
                channel.writeAndFlush(Unpooled.copiedBuffer(data));
                if (StringUtils.isBlank(id))
                    System.out.println("发送数据：" + DataConvertor.Byte2String(data));
                else
                    System.out.printf("[%s]发送数据：%s\n", id, DataConvertor.Byte2String(data));
                return true;
            } else {
                if (StringUtils.isBlank(id))
                    System.out.println("数据发送失败：" + DataConvertor.Byte2String(data));
                else
                    System.out.printf("[%s]数据发送失败：%s\n", id, DataConvertor.Byte2String(data));
                return false;
            }
        } else {
            throw new RuntimeException("data is invalid");
        }
    }
}
